package dy.com.收发并行.Client;

import dy.com.收发并行.Client.bean.ServerInfo;
import dy.com.收发并行.Util.CloseUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.rmi.server.ExportException;

public class TCPClient {
    static void linkwith(ServerInfo serverInfo) throws IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(3000);
        //连接
        socket.connect(new InetSocketAddress(InetAddress.getByName(serverInfo.getIp()), serverInfo.getPort()), 3000);

        System.out.println("客户端已经发起连接");
        //启动读线程
        ReadHandler readHandler = new ReadHandler(socket.getInputStream());
        readHandler.start();
        // write阻塞
        write(socket);


        readHandler.exit();
        socket.close();
        System.out.println("客户端已退出");

    }

    static void write(Socket socket) throws IOException {

        //得到键盘输入流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        //得到socket输出流
        PrintStream printStream = new PrintStream(socket.getOutputStream());


        while (true) {
            String str = bufferedReader.readLine();

            printStream.println(str);
            //从键盘读取到结束，退出
            if (str.equals("00bye00")) {
                break;
            }
        }
        printStream.close();
        bufferedReader.close();
        System.out.println("客户端已经退出");
    }

    private static class ReadHandler extends Thread {
        InputStream inputStream;
        boolean finish = false;

        ReadHandler(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                while (!finish) {

                    String str = null;
                    try {
                        str = bufferedReader.readLine();
                    } catch (SocketTimeoutException e) {
                        continue;
                    }

                    if (str == null) {
                        System.out.println("连接已经关闭，无法读取数值");
                        break;
                    } else {
                        System.out.println(str);
                    }


                }
            }catch (Exception e){
                if (!finish) {
                    e.printStackTrace();
                }
            }
            finally {
                CloseUtils.close(inputStream);
                CloseUtils.close(bufferedReader);
            }

        }

        void exit() {
            finish = true;
            CloseUtils.close(inputStream);
        }
    }
}
